package zdc.ui {
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.TransformGestureEvent;

import zdc.interfaces.IGestural;

/**
 *
 * @author Metal Slime
 */
public class MakeGestural {
    /**
     * 设置
     * @param    gs
     */
    public static function setup(gs:IGestural):void {
        gs.panable && gs.addEventListener(TransformGestureEvent.GESTURE_PAN, onPan);
        gs.zoomable && gs.addEventListener(TransformGestureEvent.GESTURE_ZOOM, onZoom);
        gs.rotatable && gs.addEventListener(TransformGestureEvent.GESTURE_ROTATE, onRotate);
        gs.addEventListener(Event.REMOVED_FROM_STAGE, onRemoved);
    }

    /**
     * 取消
     * @param    gs
     */
    public static function setdown(gs:IGestural):void {
        gs.removeEventListener(Event.REMOVED_FROM_STAGE, onRemoved);
        gs.removeEventListener(TransformGestureEvent.GESTURE_PAN, onPan);
        gs.removeEventListener(TransformGestureEvent.GESTURE_ROTATE, onRotate);
        gs.removeEventListener(TransformGestureEvent.GESTURE_ZOOM, onZoom);
    }

    /**
     * 缩放
     * @param    e
     */
    private static function onZoom(e:TransformGestureEvent):void {
        var gs:IGestural = e.currentTarget as IGestural;
        var sx:Number = gs.scaleX;
        var sy:Number = gs.scaleY;
        sx *= e.scaleX;
        if (sx > gs.maxZoom) {
            sx = gs.maxZoom;
        }
        else if (sx < gs.minZoom) {
            sx = gs.minZoom;
        }
        gs.scaleX = gs.scaleY = sx;
    }

    /**
     * 旋转
     * @param    e
     */
    private static function onRotate(e:TransformGestureEvent):void {
        var gs:IGestural = e.currentTarget as IGestural;
        var rot:Number = gs.rotation;
        gs.rotation += e.rotation;
    }

    /**
     * 平摇
     * @param    e
     */
    private static function onPan(e:TransformGestureEvent):void {
        var gs:IGestural = e.currentTarget as IGestural;
        if (gs.horPanable) {
            gs.x += e.offsetX;
        }
        if (gs.verPanable) {
            gs.y += e.offsetY;
        }
    }

    /**
     * 舞台中删除
     */
    private static function onRemoved(e:Event):void {
        var gs:IGestural = e.currentTarget as IGestural;
        setdown(gs);
    }
}

}